﻿Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop
Imports System.Threading
Imports System.IO
Imports System.ComponentModel

Public Class frmTiaomaBiaoqian
    Dim fileName As String
    Structure DataItem
        Dim num As String
        Dim 站点 As String
    End Structure
    Structure myData
        Dim data As List(Of DataItem)
        Sub New()
            Me.data = New List(Of DataItem)
        End Sub
    End Structure
    Dim dataList As New List(Of myData)
    Dim PageCount As Integer
    Private Delegate Sub DLShowMessage(ByVal msg As String)
    Private Delegate Sub DLShowProgress(ByVal value As Double, ByVal Max As Double, ByVal tipString As String)
    Private Delegate Sub DLCreateCompleted()
    Dim myTitle As String = Me.Text
    Private Sub frmTiaomaBiaoqian_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ChangeButtonFromFrm(Me)
        myTitle = Me.Text
    End Sub

    Private Sub Btn_OpenFile_Click(sender As Object, e As EventArgs) Handles Btn_OpenFile.Click
        Dim dialog As New OpenFileDialog()
        dialog.Title = "打开数据文件"
        dialog.Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx"
        If (dialog.ShowDialog(Me) = DialogResult.OK) Then
            TB_FileName.Text = dialog.FileName
            TB_FileName.SelectionStart = TB_FileName.Text.Length
            fileName = TB_FileName.Text
        End If
    End Sub
    Dim Createth As Thread
    Dim IsCreating As Boolean = False
    Private Sub Btn_Create_Click(sender As Object, e As EventArgs) Handles Btn_Create.Click
        Try
            PageCount = Convert.ToInt32(TB_Count.Text)
            setObjectEnabled(False)
            Createth = New Thread(New ThreadStart(AddressOf CreateThread))
            Createth.Start()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub CreateThread()
        Try
            IsCreating = True
            Dim app As New Excel.Application()
            Dim wb As Workbook = app.Workbooks.Open(fileName)
            Dim sCount As Integer = wb.Worksheets.Count
            Dim lCount As Double
            dataList = New List(Of myData)
            For i = 1 To sCount Step 1
                Dim curSheet As Worksheet = DirectCast(wb.Worksheets.Item(i), Worksheet)
                Dim zd As String = curSheet.Name
                Dim rCount As Integer = curSheet.UsedRange.Rows.Count
                Dim curData As New myData
                curData.data = New List(Of DataItem)
                For j = 2 To rCount Step 1
                    Dim tmpItem As New DataItem
                    tmpItem.站点 = zd
                    tmpItem.num = curSheet.Cells(j, 5).value
                    curData.data.Add(tmpItem)
                    Me.Invoke(New DLShowProgress(AddressOf ShowProgress), j, rCount, "任务进度：" + i.ToString() + "/" + sCount.ToString())
                    lCount += 1
                Next
                dataList.Add(curData)
            Next
            Dim saveFileName As String = getSaveFileName()
            Dim fs As New FileStream(saveFileName, FileMode.Create, FileAccess.Write)
            Dim fw As New StreamWriter(fs, System.Text.Encoding.UTF8)
            Dim lIndex As Double
            For Each item As myData In dataList
                Dim curIndex As Integer = 0
                For i = 0 To item.data.Count - 1 Step 1
                    Try
                        Dim pItem As DataItem = item.data.Item(i)
                        If (curIndex = 0) Then
                            fw.WriteLine(pItem.num)
                            If (i + PageCount - 1 < item.data.Count) Then
                                fw.WriteLine(item.data.Item(i + PageCount - 1).num)
                            Else
                                fw.WriteLine(item.data.Item(item.data.Count - 1).num)
                            End If
                            fw.WriteLine(pItem.站点)
                        End If
                    Catch es As Exception
                        writeErrorMessage(es.Message + "--" + item.data.Item(0).站点)
                    End Try
                    curIndex += 1
                    If (curIndex = PageCount) Then curIndex = 0
                    lIndex += 1
                    Me.Invoke(New DLShowProgress(AddressOf ShowProgress), lIndex, lCount, "创建数据")
                Next
            Next
            fw.Close()
            fs.Close()
            wb.Close()
            app.Quit()
            IsCreating = False
            Try
                Me.Invoke(New DLCreateCompleted(AddressOf CreateCompleted))
                Dim th As Threading.Thread = Threading.Thread.CurrentThread
                th.Abort()
            Catch
            End Try
        Catch ex As Exception
            IsCreating = False
            Me.Invoke(New DLShowMessage(AddressOf showMessage), ex.Message)
            Try
                Dim th As Threading.Thread = Threading.Thread.CurrentThread
                th.Abort()
            Catch
            End Try
        End Try
    End Sub
    Private Sub writeErrorMessage(ByVal errMsg As String)
        Dim fs As New FileStream(System.Reflection.Assembly.GetExecutingAssembly().Location + "\log.txt", FileMode.Append, FileAccess.Write)
        Dim fw As New StreamWriter(fs, System.Text.Encoding.UTF8)
        fw.WriteLine(DateTime.Now.ToString() + "  " + errMsg)
        fw.Close()
        fs.Close()
    End Sub
    Private Sub CreateCompleted()
        setObjectEnabled(True)
        Me.Text = myTitle
    End Sub
    Private Sub ShowProgress(ByVal value As Double, ByVal Max As Double, ByVal tipString As String)
        Try
            Prog.Maximum = Max
            Prog.Value = value
            If (tipString IsNot Nothing And tipString.Length > 0 And Me.Text <> (myTitle + "--" + tipString)) Then
                Me.Text = myTitle + "--" + tipString
            End If
        Catch ex As Exception
            ' MsgBox(ex.Message)
        End Try
    End Sub
    Private Sub showMessage(ByVal msg As String)
        If (msg = "正在中止线程。") Then Return
        MsgBox(msg, MsgBoxStyle.OkOnly, "错误")
    End Sub
    Private Function getSaveFileName() As String
        Dim lIndex As Integer = fileName.LastIndexOf(".")
        If (lIndex > 0) Then
            Return fileName.Substring(0, lIndex) + ".txt"
        Else
            Return fileName + ".txt"
        End If
    End Function
    Private Sub setObjectEnabled(ByVal value As Boolean)
        Me.Btn_Create.Enabled = value
        Me.Btn_OpenFile.Enabled = value
        Me.TB_Count.Enabled = value
        Me.TB_FileName.Enabled = value
    End Sub

    Private Sub frmTiaomaBiaoqian_Closed(sender As Object, e As EventArgs) Handles Me.Closed

    End Sub

    Private Sub frmTiaomaBiaoqian_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        If (IsCreating) Then
            If MessageBox.Show(Me, "数据生成操作未结束，是否继续退出？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
                If (Createth IsNot Nothing) Then
                    Try
                        Createth.Abort()
                    Catch
                    End Try
                End If
            Else
                e.Cancel = True
            End If
        End If
    End Sub
End Class